<script setup>
import {onMounted, onUnmounted, ref} from 'vue'
import { useRouter } from 'vue-router'
import { showToast, showLoadingToast, closeToast } from 'vant'
import axios from 'axios'
import { useUserWebSocketStore } from '../stores/websocket'

const router = useRouter()
const wsStore = useUserWebSocketStore()

// 身份证正面
const frontFileList = ref([])
// 身份证反面
const backFileList = ref([])

// 上传后的图片URL
const frontImageUrl = ref('')
const backImageUrl = ref('')

// OCR识别结果
const ocrResult = ref(null)

// 上传状态
const isUploading = ref(false)

// 七牛云上传配置
const qiniuUploadUrl = 'https://upload-z1.qiniup.com'

// 上传图片到七牛云
const uploadToQiniu = async (file) => {
  try {
    console.log('开始上传到七牛云，文件信息:', {
      name: file.file.name,
      size: file.file.size,
      type: file.file.type
    })
    
    if (!updata.value.token) {
      throw new Error('上传token未获取，请稍后重试')
    }
    
    const formData = new FormData()
    formData.append('file', file.file)
    formData.append('token', updata.value.token)

    console.log('发送上传请求到:', qiniuUploadUrl)
    console.log('FormData内容:', {
      file: file.file.name,
      token: updata.value.token.substring(0, 20) + '...'
    })

    const response = await axios.post(qiniuUploadUrl, formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      },
      timeout: 30000 // 30秒超时
    })

    console.log('七牛云返回数据:', response.data)
    
    if (response.data.error) {
      throw new Error(`七牛云上传失败: ${response.data.error}`)
    }
    
    return response.data
  } catch (error) {
    console.error('上传失败详情:', {
      message: error.message,
      response: error.response?.data,
      status: error.response?.status
    })
    
    if (error.response?.data?.error) {
      throw new Error(`上传失败: ${error.response.data.error}`)
    } else if (error.code === 'ECONNABORTED') {
      throw new Error('上传超时，请检查网络连接')
    } else {
      throw new Error(`上传失败: ${error.message}`)
    }
  }
}

// 返回上一页
const goBack = () => {
  router.back()
}

// 正面图片上传前
const beforeReadFront = (file) => {
  if (file.type !== 'image/jpeg' && file.type !== 'image/png' && file.type !== 'image/jpg') {
    showToast('请上传 jpg/png 格式图片')
    return false
  }
  if (file.size > 5 * 1024 * 1024) {
    showToast('图片大小不能超过 5MB')
    return false
  }
  return true
}

// 反面图片上传前
const beforeReadBack = (file) => {
  if (file.type !== 'image/jpeg' && file.type !== 'image/png' && file.type !== 'image/jpg') {
    showToast('请上传 jpg/png 格式图片')
    return false
  }
  if (file.size > 5 * 1024 * 1024) {
    showToast('图片大小不能超过 5MB')
    return false
  }
  return true
}

const updata=ref({"token":''})

// 七牛云配置
const getqntoken=()=>{
  axios.get('http://localhost:8000/user/qiniu').then(res=>{
    console.log('获取七牛云token响应:', res.data)
    if (res.data.code === 10000) {
      updata.value.token = res.data.data
      console.log('七牛云token获取成功:', updata.value.token.substring(0, 50) + '...')
    } else {
      console.error('获取七牛云token失败:', res.data)
      showToast('获取上传凭证失败，请刷新页面重试')
    }
  }).catch(error => {
    console.error('获取七牛云token异常:', error)
    showToast('网络错误，请检查网络连接')
  })
}

// WebSocket 消息处理
const handleIdentityMessage = (messageData) => {
  try {
    // 处理 OCR 识别结果
    if (messageData.type === 'ocr_complete') {
      console.log('身份证识别完成:', messageData)
      // 更新本地存储的认证状态
      localStorage.setItem('user_verified', 'true')
      // 收到消息后关闭 WebSocket 连接
      wsStore.disconnectIdentityVerification()
      console.log('UpPicture: 身份认证完成，已关闭 WebSocket 连接')
    } else if (messageData.type === 'ocr_failed') {
      console.log('身份证识别失败:', messageData)
      // 失败时不做任何提示，只记录日志
    }
  } catch (error) {
    console.error('处理实名认证消息失败:', error)
  }
}

// 初始化 WebSocket - 在用户点击提交后建立连接
const initWebSocket = () => {
  // 确保用户已登录
  const userId = localStorage.getItem('user_id')
  if (!userId) {
    console.warn('用户未登录，无法建立实名认证 WebSocket 连接')
    return
  }

  // 在实名认证页面建立独立的 WebSocket 连接
  if (!wsStore.isIdentityConnected) {
    wsStore.initIdentityVerification()
  }

  // 注册消息处理器
  wsStore.registerIdentityMessageHandler('identity_verification', handleIdentityMessage)
}

onMounted(() => {
  getqntoken()
  // 不再在页面加载时建立 WebSocket 连接
})

onUnmounted(() => {
  // 移除消息处理器（但不断开连接，因为跳转到审核中页面后仍需要接收消息）
  wsStore.unregisterIdentityMessageHandler('identity_verification')
  // 注意：不在这里断开连接，让连接保持以便在审核中页面接收消息
})

// 正面图片读取后
const afterReadFront = async (file) => {
  console.log('正面图片读取:', file)
  file.status = 'uploading'
  file.message = '上传中...'

  try {
    // 检查token是否已获取
    if (!updata.value.token) {
      console.log('Token未获取，重新获取...')
      await new Promise((resolve, reject) => {
        getqntoken()
        // 等待token获取完成
        const checkToken = () => {
          if (updata.value.token) {
            resolve()
          } else {
            setTimeout(checkToken, 100)
          }
        }
        checkToken()
        // 5秒超时
        setTimeout(() => reject(new Error('获取token超时')), 10000)
      })
    }

    // 上传到七牛云
    const result = await uploadToQiniu(file)
    console.log('正面上传成功:', result)

    // 保存图片key
    const imageKey = result.key || ''
    frontImageUrl.value = imageKey

    file.status = 'done'
    file.message = ''
    showToast('正面照片上传成功')
  } catch (error) {
    console.error('正面上传失败:', error)
    file.status = 'failed'
    file.message = '上传失败'
    showToast(error.message || '上传失败，请重试')
    // 移除失败的文件
    frontFileList.value = []
  }
}

// 反面图片读取后
const afterReadBack = async (file) => {
  console.log('反面图片读取:', file)
  file.status = 'uploading'
  file.message = '上传中...'

  try {
    // 检查token是否已获取
    if (!updata.value.token) {
      console.log('Token未获取，重新获取...')
      await new Promise((resolve, reject) => {
        getqntoken()
        // 等待token获取完成
        const checkToken = () => {
          if (updata.value.token) {
            resolve()
          } else {
            setTimeout(checkToken, 100)
          }
        }
        checkToken()
        // 5秒超时
        setTimeout(() => reject(new Error('获取token超时')), 5000)
      })
    }

    // 上传到七牛云
    const result = await uploadToQiniu(file)
    console.log('反面上传成功:', result)

    // 保存图片key
    const imageKey = result.key || ''
    backImageUrl.value = imageKey

    file.status = 'done'
    file.message = ''
    showToast('反面照片上传成功')
  } catch (error) {
    console.error('反面上传失败:', error)
    file.status = 'failed'
    file.message = '上传失败'
    showToast(error.message || '上传失败，请重试')
    // 移除失败的文件
    backFileList.value = []
  }
}

// 删除正面图片
const onDeleteFront = () => {
  frontFileList.value = []
  frontImageUrl.value = ''
  showToast('已删除正面照片')
}

// 删除反面图片
const onDeleteBack = () => {
  backFileList.value = []
  backImageUrl.value = ''
  showToast('已删除反面照片')
}

// 提交认证
const submitVerify = async () => {
  if (frontFileList.value.length === 0) {
    showToast('请上传身份证正面照片')
    return
  }
  if (backFileList.value.length === 0) {
    showToast('请上传身份证反面照片')
    return
  }
  
  // 获取用户ID
  const userId = localStorage.getItem('user_id')
  if (!userId) {
    showToast('请先登录')
    router.push('/user/login')
    return
  }
  
  // 在提交时建立 WebSocket 连接
  initWebSocket()
  
  isUploading.value = true
  showLoadingToast({ message: '正在提交身份证信息...', forbidClick: true, duration: 0 })
  
  try {
    // 将身份证URL存入Redis队列
    const pushResp = await axios.get(
      `http://localhost:8000/user/idcard?url=http://t4waqd60k.hb-bkt.clouddn.com/${frontImageUrl.value}&user_id=${userId}`
    )
    
    closeToast()
    isUploading.value = false
    
    if (pushResp.data.code === 200) {
      // 显示提示信息并跳转到审核中页面
      showToast({
        message: '正在实名认证中，请等待',
        type: 'success',
        duration: 2000
      })
      // 延迟跳转以确保提示显示
      setTimeout(() => {
        router.push('/pending-verification')
      }, 2000)
    } else {
      showToast('提交失败：' + (pushResp.data.message || '请重试'))
    }
  } catch (error) {
    closeToast()
    isUploading.value = false
    showToast('提交失败：' + (error.response?.data?.message || error.message || '请重试'))
  }
}
</script>

<template>
  <div class="identity-verify-page">
    <!-- 顶部导航栏 -->
    <van-nav-bar
      title="身份认证"
      left-arrow
      @click-left="goBack"
      class="nav-bar"
    />

    <!-- 内容区域 -->
    <div class="content">
      <!-- 提示信息 -->
      <div class="tips-card">
        <van-icon name="info-o" size="18" color="#FF6B00" />
        <div class="tips-text">
          <div>请上传本人身份证照片</div>
          <div class="tips-sub">请确保照片清晰，信息完整</div>
        </div>
      </div>

      <!-- 身份证正面 -->
      <div class="upload-section">
        <div class="upload-title">
          <span>身份证正面</span>
          <span class="required">*</span>
        </div>
        <van-uploader
          v-model="frontFileList"
          :max-count="1"
          :before-read="beforeReadFront"
          :after-read="afterReadFront"
          @delete="onDeleteFront"
          class="uploader"
        >
          <div class="upload-card" v-if="frontFileList.length === 0">
            <div class="upload-icon">
              <van-icon name="plus" size="40" color="#999" />
            </div>
            <div class="upload-text">上传身份证正面</div>
            <div class="upload-hint">包含国徽的一面</div>
          </div>
        </van-uploader>
      </div>

      <!-- 身份证反面 -->
      <div class="upload-section">
        <div class="upload-title">
          <span>身份证反面</span>
          <span class="required">*</span>
        </div>
        <van-uploader
          v-model="backFileList"
          :max-count="1"
          :before-read="beforeReadBack"
          :after-read="afterReadBack"
          @delete="onDeleteBack"
          class="uploader"
        >
          <div class="upload-card" v-if="backFileList.length === 0">
            <div class="upload-icon">
              <van-icon name="plus" size="40" color="#999" />
            </div>
            <div class="upload-text">上传身份证反面</div>
            <div class="upload-hint">包含有效期的一面</div>
          </div>
        </van-uploader>
      </div>

      <!-- 注意事项 -->
      <div class="notice-section">
        <div class="notice-title">注意事项：</div>
        <div class="notice-item">1. 请上传本人真实有效的二代身份证照片</div>
        <div class="notice-item">2. 图片需清晰完整，四角完整可见</div>
        <div class="notice-item">3. 支持 JPG、PNG 格式，大小不超过 5MB</div>
        <div class="notice-item">4. 需同时上传正面和反面照片</div>
        <div class="notice-item">5. 审核通过后不可修改，请仔细核对</div>
      </div>
    </div>

    <!-- 底部提交按钮 -->
    <div class="submit-section">
      <van-button
        type="primary"
        block
        round
        @click="submitVerify"
        :loading="isUploading"
        :disabled="isUploading"
        class="submit-btn"
      >
        提交认证
      </van-button>
    </div>
  </div>
</template>

<style scoped>
.identity-verify-page {
  min-height: 100vh;
  background: #f5f5f5;
  padding-bottom: 80px;
}

/* 导航栏 */
.nav-bar {
  --van-nav-bar-background: white;
  --van-nav-bar-title-text-color: #333;
}

/* 内容区域 */
.content {
  padding: 16px;
}

/* 提示卡片 */
.tips-card {
  background: #FFF7E6;
  border-radius: 8px;
  padding: 12px 16px;
  display: flex;
  align-items: flex-start;
  gap: 12px;
  margin-bottom: 16px;
}

.tips-text {
  flex: 1;
  font-size: 14px;
  color: #FF6B00;
}

.tips-sub {
  font-size: 12px;
  color: #FF9500;
  margin-top: 4px;
}

/* 上传区域 */
.upload-section {
  margin-bottom: 24px;
}

.upload-title {
  font-size: 15px;
  font-weight: 600;
  color: #333;
  margin-bottom: 12px;
}

.required {
  color: #ff4444;
  margin-left: 4px;
}

.uploader {
  width: 100%;
}

:deep(.van-uploader__wrapper) {
  width: 100%;
}

:deep(.van-uploader__preview),
:deep(.van-uploader__upload) {
  width: 100%;
  margin: 0;
}

:deep(.van-uploader__preview-image) {
  width: 100%;
  height: 220px;
  object-fit: cover;
  border-radius: 8px;
  background: #f8f8f8;
}

.upload-card {
  width: 100%;
  height: 220px;
  background: white;
  border: 2px dashed #ddd;
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s;
}

.upload-card:hover {
  border-color: #00D4AA;
  background: #f8fff8;
}

.upload-icon {
  margin-bottom: 12px;
}

.upload-text {
  font-size: 15px;
  color: #333;
  margin-bottom: 6px;
  font-weight: 500;
}

.upload-hint {
  font-size: 13px;
  color: #999;
}

/* 注意事项 */
.notice-section {
  background: white;
  border-radius: 8px;
  padding: 16px;
  margin-top: 20px;
}

.notice-title {
  font-size: 15px;
  font-weight: 600;
  color: #333;
  margin-bottom: 12px;
}

.notice-item {
  font-size: 13px;
  color: #666;
  line-height: 1.8;
  padding-left: 0;
}

/* 底部提交按钮 */
.submit-section {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: white;
  padding: 12px 16px;
  box-shadow: 0 -2px 12px rgba(0, 0, 0, 0.08);
}

.submit-btn {
  --van-button-primary-background: linear-gradient(135deg, #00D4AA 0%, #00B894 100%);
  --van-button-primary-border-color: transparent;
  height: 48px;
  font-size: 16px;
  font-weight: 600;
}

/* 响应式 */
@media (max-width: 375px) {
  .upload-card {
    height: 200px;
  }
  
  :deep(.van-uploader__preview-image) {
    height: 200px;
  }
}
</style>

